package com.example.teamtribe.main.club.clubintroduce.media.photo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.teamtribe.R;
import com.example.teamtribe.base.BaseActivity;
import com.example.teamtribe.common.Back;
import com.example.teamtribe.database.Media;
import com.example.teamtribe.event.Refresh;
import com.example.teamtribe.main.club.clubintroduce.GridSpacingItemDecoration;
import com.example.teamtribe.main.club.clubintroduce.media.MediaModel;
import com.example.teamtribe.main.club.clubintroduce.media.UpdateMediaActivity;
import com.example.teamtribe.utils.Utility;
import com.example.zhouwei.library.CustomPopWindow;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class PhotoActivity extends BaseActivity implements PhotoContract.View{
    private RefreshLayout refreshLayout;
    private Media media;
    private PhotoGridAdapter adapter;
    private RecyclerView recyclerView;
    private ImageView more;
    private CustomPopWindow mCustomPopWindow;
    private PhotoContract.Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        presenter = new PhotoPresenter(this);
        more=(ImageView)findViewById(R.id.iv_more);
        refreshLayout = (RefreshLayout)findViewById(R.id.rl_photo);
        recyclerView = findViewById(R.id.rv_media_list);

        media=getIntent().getParcelableExtra("media");
        ((TextView)findViewById(R.id.tv_title)).setText(media.getName());
        ImageView ivCover=(ImageView)findViewById(R.id.iv_cover);
        ((TextView)findViewById(R.id.tv_description)).setText(media.getDescription());
        Glide.with(this).load(Utility.getUri(media.getCover())).into(ivCover);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 5, false));
        recyclerView.setNestedScrollingEnabled(false);
        adapter=new PhotoGridAdapter(PhotoGridAdapter.PHOTO);
        recyclerView.setAdapter(adapter);

        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View contentView = LayoutInflater.from(PhotoActivity.this).inflate(R.layout.pop_club_photo,null);
                //处理popWindow 显示内容
                handleLogic(contentView);
                //创建并显示popWindow
                mCustomPopWindow= new CustomPopWindow.PopupWindowBuilder(PhotoActivity.this)
                        .setView(contentView)
                        .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                        .setBgDarkAlpha(0.7f) // 控制亮度
                        .create()
                        .showAsDropDown(more,0,0);
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.getPhotos(media.getTeamId(),media.getRealId(),0,12);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                presenter.getMore(media.getTeamId(),media.getRealId(),adapter.getItemCount(),6);
                //refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败

            }
        });
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        presenter.hasAuthority(media.getTeamId(),Utility.getUser().getRealId());//获取是否有权限
        presenter.getPhotos(media.getTeamId(),media.getRealId(),0,12);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void refresh(Refresh r) {
        presenter.getPhotos(media.getTeamId(),media.getRealId(),0,12);
        if(r.getType()==Refresh.PHOTOACTIVITY){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    private void handleLogic(View contentView){
        contentView.findViewById(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
//        Button upLoad=findViewById(R.id.bt_upload);
//        upLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(PhotoActivity.this,AddPhotoActivity.class);
                intent.putExtra("media",media);
                startActivity(intent);
            }
        });
        contentView.findViewById(R.id.tv_alter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCustomPopWindow.dissmiss();
                Intent intent=new Intent(PhotoActivity.this,UpdateMediaActivity.class);
                intent.putExtra("media",media);
                intent.putExtra("type",1);
                startActivityForResult(intent,1);
            }
        });
        contentView.findViewById(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCustomPopWindow.dissmiss();
                AlertDialog.Builder dialog=new AlertDialog.Builder(PhotoActivity.this);
                dialog.setTitle("确认删除");
                dialog.setMessage("确认删除相册 "+ media.getName()+" 吗？");
                dialog.setCancelable(true);
                dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MediaModel.getInstance().deleteMedia(Utility.getToken(), media.getTeamId(), media.getRealId(), new Back() {
                            @Override
                            public void success(@Nullable Bundle bundle) {
                                EventBus.getDefault().post(new Refresh(Refresh.ALBUMFRAGMENT));
                                finish();
                            }

                            @Override
                            public void failure(String meg) {
                                hideProgress();
                                showToast(meg);
                            }
                        });
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1:
                if(resultCode==RESULT_OK){
                    String name=data.getStringExtra("mediaName");
                    String cover=data.getStringExtra("mediaCover");
                    String description=data.getStringExtra("mediaDescription");
                    ((TextView)findViewById(R.id.tv_title)).setText(name);
                    ImageView ivCover=(ImageView)findViewById(R.id.iv_cover);
                    ((TextView)findViewById(R.id.tv_description)).setText(description);
                    Glide.with(this).load(Utility.getUri(cover)).into(ivCover);
                }
                break;
            default:
        }
    }

    @Override
    public void addPhoto(String photo) {
        adapter.addPhoto(photo);
        final int position=adapter.getItemCount()-1;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //adapter.notifyDataSetChanged();
                adapter.notifyItemChanged(position);
            }
        });
    }

    @Override
    public void clearPhotos() {
        adapter.clear(PhotoGridAdapter.PHOTO);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void finishRefresh() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh(0);
    }

    @Override
    public void next() {

    }

    @Override
    public void setVisibility() {
        if(more.getVisibility()==View.GONE){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    more.setVisibility(View.VISIBLE);
                }
            });
        }

    }
}
